import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from CloudGuardian.models import BindRelationship
from SecureHelperServer.settings import formatResponseData
from utils.conf import Response
from utils.custom import MyJWTAuthentication


class GetBindRelationship(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        云监护-获取用户监护关系信息
        """
        data = copy.deepcopy(formatResponseData)
        try:
            user = request.user

            myGuardianUserList = [i.guardianUser for i in BindRelationship.objects.filter(wardUser=user)]
            myWardUserList = [i.wardUser for i in BindRelationship.objects.filter(guardianUser=user)]

            bindRelationshipInfo = {}

            guardianUserInfoList = []
            for guardianUser in myGuardianUserList:
                guardianUserInfoList.append({
                    "uid": guardianUser.uid,
                    "username": guardianUser.username,
                    "email": guardianUser.email,
                })
            bindRelationshipInfo["guardianUserInfoList"] = guardianUserInfoList

            wardUserInfoList = []
            for wardUser in myWardUserList:
                wardUserInfoList.append({
                    "uid": wardUser.uid,
                    "username": wardUser.username,
                    "email": wardUser.email,
                })
            bindRelationshipInfo["wardUserInfoList"] = wardUserInfoList

            data["data"]["bindRelationshipInfo"] = bindRelationshipInfo
            return Response(data=data, loggerMsg=f"云监护-获取用户监护关系信息：获取成功，uid={user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
